package com.ruoyi.erp.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.erp.domain.*;
import com.ruoyi.erp.service.IBzFaCardsService;
import com.ruoyi.erp.service.ILedyBacFeeConfigService;
import com.ruoyi.erp.service.ILedyBudgetService;
import com.ruoyi.erp.util.api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 预算数据接收Controller
 */
@RestController
@RequestMapping("/erp/budget")
public class BudgetPullController extends BaseController {
    @Autowired
    private IBzFaCardsService bzFaCardsService;
    @Autowired
    private api api;
    @Autowired
    private ILedyBudgetService ledyBudgetService;
    @Autowired
    private ILedyBacFeeConfigService configService;

    /**
     * 资产推送
     */
    @PreAuthorize("@ss.hasPermi('erp:cards:add')")
    @Log(title = "资产推送", businessType = BusinessType.IMPORT)
    @GetMapping("/push/{ids}")
    public AjaxResult faPush(@PathVariable Long[] ids) {
        List<BzFaCards> list = bzFaCardsService.selectBzFaCardsList(ids);
//        BzFaCardsParam param = new BzFaCardsParam();
//        param.setBill_date(DateUtil.format(new Date(), "yyyy-MM-dd"));
//        param.setBill_iOptType("新增");
//        List<Bills> bills = new ArrayList<>();
//        Bills bill= new Bills();
//        bill.setBill_code(UUID.fastUUID().toString());
//        bill.setVouchers(BeanUtil.copyToList(list, Object.class));
//        bills.add(bill);
//        param.setBills(bills);
//        List<BzFaCardsPush> pushList = new ArrayList<>();
        list.forEach(item -> {
            BzFaCardsPush push = new BzFaCardsPush();
            push.setVoucherNo(item.getsCardID().toString());
            push.setAssetStyle(item.getsStyle());
            push.setAssetUseName(item.getsStatusID());
            push.setCategoryCode(item.getsTypeNum());
            push.setDepreMonth(item.getlLife().toString());
            push.setFullName(item.getsAssetName());
            push.setGetDate(DateUtil.format(item.getdStartdate(), "yyyy-MM-dd"));
            push.setInitialNumber(item.getsAssetNum());
            push.setLocationName(item.getsSite());
            DecimalFormat df1 = new DecimalFormat("#.00");
            push.setNetValue(df1.format(item.getDblBV()));
            push.setPolicyNo(item.getsCardNum());
            push.setQty("1");
            push.setTotalMoney(df1.format(item.getDblValue()));
            push.setUnitPrice(df1.format(item.getDblValue()));
            push.setUseDepartment(item.getsDeptNames());
            faPushHttp(push, item);
//            new Thread(() -> faPushHttp(push, item)).start();
        });
        return toAjax(1);
    }

    private void faPushHttp(BzFaCardsPush push, BzFaCards item) {
        Map<String, String> heads = new HashMap<>();
        heads.put("Content-Type", "application/json;charset=UTF-8");
        logger.debug(JSONUtil.toJsonStr(push));
        HttpResponse response = HttpRequest.post(api.getAddFa())
                .headerMap(heads, false)
                .body(JSONUtil.toJsonStr(push))
                .timeout(5 * 60 * 1000)
                .execute();
        logger.debug(response.body());
        ResultData resultData = JSONUtil.toBean(response.body(), ResultData.class);
        if (resultData.getErrorcode() == 0) {
            item.setIsPush(1);
        } else {
            item.setIsPush(3);
        }
        bzFaCardsService.updateBzFaCards(item);
    }

    @PostMapping("/pushNotice")
    public AjaxResult pushNotice(@RequestBody List<LedyBudget> ledyBudget) {
        logger.debug(JSONUtil.toJsonStr(ledyBudget));

        ledyBudget.forEach(item -> {
            LedyBacFeeConfig config = new LedyBacFeeConfig();
            config.setItemId(item.getCitemId());
            List<LedyBacFeeConfig> configs = configService.selectLedyBacFeeConfigList(config);
            if (configs.isEmpty()) {
                config.setIshare(0);
                config.setRecordCode("记");
                config.setRecordCate("借");
                config.setRecordSchema("budget");
                config.setStatus("N");
                config.setRemark("同步添加");
                config.setcBusType1(item.getcBusType1());
                config.setcBusType2(item.getcBusType2());
                config.setcBusType3(item.getcBusType3());
                config.setcBusType4(item.getcBusType4());
                config.setcBusType1Id(item.getcBusType1Id());
                config.setcBusType2Id(item.getcBusType2Id());
                config.setcBusType3Id(item.getcBusType3Id());
                config.setcBusType4Id(item.getcBusType4Id());
                config.setItemId(item.getCitemId());
                config.setItemName(item.getCitemName());
                configService.insertLedyBacFeeConfig(config);
                config.setRecordCate("贷");
                configService.insertLedyBacFeeConfig(config);
            } else
                configs.forEach(config1 -> {
                    if (config1.getIshare() == 1) {
                        item.setIshare(config1.getIshare());
                    }
                });
            ledyBudgetService.insertLedyBudget(item);
        });


        return success("1");
    }

}
